package com.example.interceptor;

import com.example.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import org.springframework.web.servlet.HandlerInterceptor;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

public class JwtInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 放行登录请求
        if (request.getRequestURI().equals("/login")) {
            return true;
        }

        // 检查token
        String token = request.getHeader("token");
        if (token == null) {
            response.setStatus(401);
            return false;
        }

        try {
            Claims claims = JwtUtils.parseToken(token);
            request.setAttribute("username", claims.getSubject());
            request.setAttribute("userId", claims.get("userId"));
            return true;
        } catch (JwtException e) {
            response.setStatus(401);
            return false;
        }
    }
} 